import sys
import os
from datetime import date
import itertools
sys.path.append(os.path.dirname(os.path.dirname(__file__)))

from tqsdk import TqApi, TqAuth, TqSim, TqBacktest, BacktestFinished
from strategies.rsrs_strategy import RSRStrategy
from utils.config_manager import ConfigManager

# 使用项目根目录的.settings
project_root = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
config = ConfigManager(config_dir=os.path.join(project_root, '.settings'))
account_config = config.get_account_config('tqsdk_account')

# 参数优化空间
param_space = {
    'rsrs_period': [18],
    'rsrs_std_period': [600],
    'long_threshold': [0.5, 0.6, 0.7, 0.8],
    'short_threshold': [-0.5, -0.6, -0.7, -0.8],
    'long_close_threshold': [0.2, -0.2],
    'short_close_threshold': [0.2, -0.2]
}

# 生成所有参数组合
param_names = list(param_space.keys())
param_values = list(param_space.values())
param_combinations = [dict(zip(param_names, combo)) for combo in itertools.product(*param_values)]

print(f"总共 {len(param_combinations)} 组参数需要测试\n")

results = []

for i, params in enumerate(param_combinations, 1):
    print(f"[{i}/{len(param_combinations)}] 测试参数: {params}")
    
    symbol_info = {
        "rb": {
            "exchange": "SHFE",
            "start_period": 20,
            **params
        }
    }
    
    api = TqApi(
        account=TqSim(init_balance=100000),
        backtest=TqBacktest(start_dt=date(2024, 1, 1), end_dt=date(2024, 6, 30)),
        auth=TqAuth(account_config['user_id'], account_config['password'])
    )
    
    strategy = RSRStrategy(api, symbol_info, market_period=60)
    
    try:
        strategy.on_bar()
    except BacktestFinished:
        account = api.get_account()
        total_return = (account.balance - 100000) / 100000
        results.append({
            'params': params,
            'return': total_return,
            'final_balance': account.balance
        })
        print(f"  收益率: {total_return:.2%}, 最终资金: {account.balance:,.0f}\n")
        api.close()

# 按收益率排序
results.sort(key=lambda x: x['return'], reverse=True)

print("\n" + "="*60)
print("优化结果 Top 5:")
print("="*60)
for i, result in enumerate(results[:5], 1):
    print(f"{i}. 收益率: {result['return']:.2%}")
    print(f"   参数: {result['params']}\n")
